/*
 * @lc app=leetcode.cn id=733 lang=typescript
 *
 * [733] 图像渲染
 */

// @lc code=start
let getCor = (x: number, y: number) => [
    [x - 1, y],
    [x + 1, y],
    [x, y - 1],
    [x, y + 1],
];
function floodFill(
    image: number[][],
    sr: number,
    sc: number,
    color: number,
    validVal?: number,
    cache = new Set<string>()
): number[][] {
    // 验证
    if (validVal === undefined) {
        validVal = image[sr][sc];
    }
    if (cache.has(`${sr},${sc}`)) return image;
    if (validVal !== image[sr][sc]) return image;

    // 赋值
    image[sr][sc] = color;
    cache.add(`${sr},${sc}`);

    // 找周围项
    getCor(sr, sc)
        .filter(([y, x]) => {
            if (x < 0 || y < 0) return false;
            if (x >= image[0].length || y >= image.length) return false;

            return true;
        })
        .forEach(([y, x]) => floodFill(image, y, x, color, validVal, cache));
    return image;
}
// @lc code=end
